package net.mikoo.seals.api.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import net.mikoo.seals.api.model.BaseResponse;
import net.mikoo.seals.api.model.ResultType;
import net.mikoo.seals.api.model.sms.SmsRequest;
import net.mikoo.seals.biz.manager.SmsManager;
import net.mikoo.seals.common.exception.ParametersException;
import net.mikoo.seals.common.exception.SendSmsException;
import net.mikoo.seals.utils.DateUtil;
import net.mikoo.seals.utils.StringUtil;
import net.mikoo.seals.utils.ValidatorUtil;
import net.sf.json.JSONObject;


@Controller
public class SmsController {

	Logger logger = Logger.getLogger(SmsController.class);
	
	private static final String SMS_DATETIME_FORMAT = "sms_code_datetime_%s";
	private static final String SMS_CODE_FORMAT = "sms_send_code_%s";
	private static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

	@Autowired
	private SmsManager smsManager;
	
	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	

	@RequestMapping("/send/sms")
	@ResponseBody
	public BaseResponse send(SmsRequest smsRequest, HttpServletRequest request) {
		BaseResponse result = new BaseResponse();
		try {
			
			if(smsRequest == null) {
				throw new ParametersException("smsRequest");
			}
			
			if(StringUtils.isBlank(smsRequest.getPhone()) || !ValidatorUtil.isMobile(smsRequest.getPhone())) {
				throw new ParametersException("手机号码输入有误");
			}
			
			String sendTime = redisTemplate.opsForValue().get(String.format(SMS_DATETIME_FORMAT, smsRequest.getPhone()));
			if(StringUtils.isNotBlank(sendTime)) {
				Date sendDatetime = DateUtil.stringToDate(sendTime.toString(), DATETIME_FORMAT);
				Date currentDatetime = DateUtil.getCurretDate();
				sendDatetime = DateUtil.addMinute(sendDatetime, 1);
				if (DateUtil.compare(sendDatetime, currentDatetime) > 0) {
					throw new ParametersException("您操作太频繁，请稍微再试");
				}
			}

			//生成短信随机码
			String smscode = StringUtil.getRandNum(6);
			JSONObject data = new JSONObject();
			data.put("code", smscode);
			String template = "SMS_147435007";
			if(!StringUtils.isBlank(smsRequest.getType()) && "resetpassword".equals(smsRequest.getType())) {
				template = "SMS_163852927";
			}
			try {
				smsManager.sendSms(smsRequest.getPhone(), template, data.toString());
				redisTemplate.opsForValue().set(String.format(SMS_DATETIME_FORMAT, smsRequest.getPhone()),DateUtil.formate(new Date(), DATETIME_FORMAT));
				redisTemplate.opsForValue().set(String.format(SMS_CODE_FORMAT, smsRequest.getPhone()), smscode);
			}catch (SendSmsException e) {
				throw new ParametersException("短信发送失败");
			}
			
			result.setResult(ResultType.SUCCESS.getValue());
		} catch (ParametersException e) {
			logger.error("",e);
			result.setResult(ResultType.ERROR.getValue());
		} catch (Exception e) {
			logger.error("",e);
			result.setResult(ResultType.ERROR.getValue());
		}
		return result;
	}
}
